利用Owin解決CORS報錯問題

個人項目是vue + ASP.NET 。在 Vue調試時,因爲vue開啓的調試用的服務器端口號 和 後臺.NET程序的端口號是不一樣的,發送Ajax請求時,就會報錯。這裏就不提報錯的緣由了,網上有不少,基本的解決方法就是爲對應的Action添加Header,好比如下代碼:html

        public ActionResult MeetingList() {

            Response.AppendHeader("Access-Control-Allow-Origin", "*");
            Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type");

            if (Request.HttpMethod.Equals("Options", StringComparison.OrdinalIgnoreCase))
            {
                return new EmptyResult();
            }

            var meetingList = _meetingRepository.GetMeetings();

            var MeetingDtoList = Mapper.Map<List<MeetingSelectDto>>(meetingList);

            return Json(MeetingDtoList, JsonRequestBehavior.AllowGet);
        }

原理雖然如此,可是要爲每個Action都添加這樣的代碼,太不友好了。vue

這時能夠使用Owin 的管道提早處理每個請求,關於Owin,又是一個大話題,請自行google。服務器

這裏給一個本身寫Owin中間件的教程連接 http://www.cnblogs.com/gaobing/p/5076089.htmlapp

我根據上面的連接,寫的代碼以下:ide

namespace WebApplication1.Middleware
{
  public class CORSMiddleware : OwinMiddleware
  {
    public CORSMiddleware(OwinMiddleware next) : base(next) {

    }

    public override Task Invoke(IOwinContext context)
    {
      
     
      context.Response.Headers.Add("Access-Control-Allow-Origin",new string[] { "*" });

      context.Response.Headers.Add("Access-Control-Allow-Headers", new string[] { "x-requested-with,content-type" });

      if (context.Request.Method.Equals("Options", StringComparison.OrdinalIgnoreCase))
      {
        return Task.FromResult<int>(0);
      }
      return Next.Invoke(context);
    }
  }
}

 

 

namespace WebApplication1.Middleware
{
  public static class AppBuilderExtension
  {
    public static IAppBuilder UseCORS(this IAppBuilder builder)
    {
      return builder.Use<CORSMiddleware>();
    
    }

  }
}

以後在Startup裏調用 UseCORS函數就能夠了!函數

相關文章
相關標籤/搜索