HttpResponseMessage 返回支持跨域

一、WebApi 跨域请求

[HttpGet]
public HttpResponseMessage Get(HttpRequestMessage request, string json)
{
   try
   {
        HttpResponseMessage response = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(new { code = 0, msg = Guid.NewGuid().ToString("N") }), Encoding.GetEncoding("UTF-8"), "application/json") };
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        response.Headers.Add("Access-Control-Allow-Headers", "*");
        response.Headers.Add("Access-Control-Allow-Methods", "*");
        return response;
    }
    catch (Exception ex)
    {
        return new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(new { code = 1, msg = ex.Message }), Encoding.GetEncoding("UTF-8"), "application/json") };
    }
}

 

posted @ 2022-05-11 14:54  陈醋当墨写尽人生酸楚  阅读(131)  评论(0编辑  收藏  举报