.NET MVC的跨域请求具体操作
一个简单的项目文件
在如图中插入以下代码
//跨域配置
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
需要安装一个包 Microsoft.AspNet.WebApi.Cors
到这里跨域基本问题就解决了,接下来演示一个基本请求操作
添加公共类common在Models中,作用是接受json保证他格式不变
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace NewsWebApplication
{
public class ResultCode
{
public bool IsSuccess { get; set; }
public int Code { get; set; }
public string Msg { get; set; }
}
public class ResultToJson
{
public static HttpResponseMessage toJson(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
}
}
示例为一个get请求接口
post请求
接下前端调用即可
此处用uniapp创建项目 方便快捷
post一样
前后端都跑起来看一下
控制台也打印出来了
到这里就完成一个简单的跨域请求
此文是做个备份,怕以后忘了,如果你看到了,缘分