简体   繁体   English

在Dot Net Core中取消/阻止路线导航

[英]Cancelling / Preventing route navigation in Dot Net Core

I've a typical API in C# Dot Net Core, where a list of orders is returned back upon receiving the ajax request of $.getJSON(apiUrl) as below: 我在C#Dot Net Core中有一个典型的API,在收到$.getJSON(apiUrl)ajax请求后,将返回订单列表,如下所示:

$.getJSON("api/Orders")
    .done(function (data) {
        // On success, 'data' contains a list of products.
        $.each(data, function (key, item) {
            // Add a list item for the product.
            $('<li>', { text: formatItem(item) }).appendTo($('#products'));
        });
    });

My controller is simply like below: 我的控制器如下所示:

    public class OrdersController 
{
    [HttpGet("api/Orders")]
    public object Orders()
    { 
        return new
        {
            .
            .
        };
    }
}

The above is fine with me. 以上对我来说很好。

My problem is, if the user entered in the browser a url like: http://localhost/api/Orders he will be getting th same output, which I want to prevent. 我的问题是,如果用户在浏览器中输入的网址是: http://localhost/api/Orders他将得到相同的输出,我想防止这种情况。

ie I need to allow the access to my API through ajax only, and need to prevent (or cancel or redirect) it if received through navigation in the browser address line. 即,我需要仅允许通过ajax访问我的API,并且如果通过浏览器地址行中的navigation接收到它,则需要阻止(或取消或重定向)它。

Thanks 谢谢

You won't be able to disallow navigation requests whole-sale. 您将无法禁止批发销售导航请求。

All you can really do is check for specific headers indicating that it's an AJAX request. 您真正要做的就是检查特定的标头,以表明这是AJAX请求。 Like X-Requested-With. 就像X-Requested-With。 But any basic http client will allow people to add it. 但是任何基本的HTTP客户端都会允许人们添加它。

Thanks for all the hits given, I solved it by the creating a middleware as below: 感谢您给予的所有成功,我通过创建如下middleware来解决了这个问题:

  1. Created a folder Middleware 创建一个文件夹Middleware
  2. Inside this new folder, I created 2 files MiddleWalewareExtensions.cs and RequestHeaderMiddleware.cs 在这个新文件夹中,我创建了2个文件MiddleWalewareExtensions.csRequestHeaderMiddleware.cs

  3. The MiddleWalewareExtensions.cs is the one defining all the middlewares we are having, in this example it is just one, the code is: MiddleWalewareExtensions.cs是定义我们拥有的所有中间件的代码,在此示例中,它只是其中之一,代码为:

     using Microsoft.AspNetCore.Builder; // for IApplicationBuilder namespace myApp.Middleware { public static class MiddlewareExtensions { public static IApplicationBuilder UseRequestHeaderMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestHeaderMiddleware>(); } ... here you can define others 

    } } }}

  4. The RequestHeaderMiddleware is the middleware that checks if url contains the word api it is executed only if the header contains user-key and this key is a valid one, otherwise an error is returned. RequestHeaderMiddleware是一种中间件,用于检查url是否包含api这个词,只有在标头包含user-key并且此密钥是有效密钥的情况下才执行该中间件,否则返回错误。 if the link does not contains the api word it is executed without a need of a user key. 如果链接不包含api字,则无需用户键即可执行该链接。

      using Microsoft.AspNetCore.Http; using System.Threading.Tasks; namespace myApp.Middleware { public class RequestHeaderMiddleware { private readonly RequestDelegate _next; public RequestHeaderMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { string url = context.Request.Path; if (url.Contains("api") && !context.Request.Headers.Keys.Contains("user-key")) { context.Response.StatusCode = 400; //Bad Request await context.Response.WriteAsync("You need a user key to be able to access this API.."); return; } else { if(context.Request.Headers["user-key"] != "28236d8ec201df516d0f6472d516d72d") { context.Response.StatusCode = 401; //UnAuthorized await context.Response.WriteAsync("Invalid User Key"); return; } } await _next.Invoke(context); } } } 
    1. In the Startup.cs file add using myApp.Middleware; Startup.cs文件中, using myApp.Middleware;添加using myApp.Middleware; then: 然后:

       public void Configure(IApplicationBuilder app) { app.UseRequestHeaderMiddleware(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); 
    2. In the JavaScript client app add the required header to the xmlhttp like: 在JavaScript client app将所需的标头添加到xmlhttp如下所示:

        xmlhttp.setRequestHeader("user-key", "28236d8ec201df516d0f6472d516d72d"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM