我在使用 IHttpClientFactory 的 .NET Core 3.1 应用程序中使用 Refit (5.1.67) 作为我的 HttpClient 包装器。
我调用的 API 使用客户端凭据令牌进行保护。
我正在用这个注册客户:
services.AddRefitClient<ISomeApiClient>().ConfigureHttpClient(c =>
c.BaseAddress = new Uri(Configuration["BaseUrlFromConfig"]));
Run Code Online (Sandbox Code Playgroud)
客户端的方法如下所示:
public interface ISomeApiClient
{
[Get("/api/somewhere")]
Task<IEnumerable<MyResponseObject>> GetItems([Header("X-User-Id")] string userId, [Header("Authorization")] string accessToken);
[Get("/api/somewhere-else")]
Task<MyResponseObject> GetItem([Header("X-User-Id")] string userId, [Header("Authorization")] string accessToken, int id);
}
Run Code Online (Sandbox Code Playgroud)
我想避免的是每次调用端点时都必须显式传递 accessToken 和 userId (如上)。理想情况下,我希望我的客户看起来像这样:
public interface ISomeApiClient
{
[Get("/api/somewhere")]
Task<IEnumerable<MyResponseObject>> GetItems();
[Get("/api/somewhere")]
Task<IEnumerable<MyResponseObject>> GetItems(int id);
}
Run Code Online (Sandbox Code Playgroud)
感觉我需要某种用于传出请求的请求中间件,我可以在其中添加这两个标头。如果它们是静态的,我只会装饰整个界面,但因为这些是行不通的运行时值。
我在文档中找不到有关此问题的任何帮助,并且希望得到任何指点。
最近我开始为我工作的公司开发一个 API。经过一些研究,我们最终使用 NLog 作为日志记录库,它有一个布局渲染器用于记录发布的请求正文,所以这很好。但是,还需要记录响应、处理和返回请求所花费的时间(因为它也会被第 3 方供应商消耗,通常它与其中一些供应商的方式是: -我单击了事情。-嗯,不,你没有)。
现在,我这些天读了很多关于中间件日志记录的内容,但有些帖子已经过时了,有些解决方案只能部分工作(查看开发人员页面时出现问题),在 github 的某个地方,我读到记录响应是不好的做法,因为它可以包含敏感数据。也许我缺少诸如遥测之类的东西?
感谢您的时间和帮助,并对我的咆哮表示歉意,在无休止的阅读测试之后,我仍然感到很焦灼。
我已经尝试过什么以及当前的问题是什么。context.Response.Body 的问题在于它是一个不可读但可写的流。为了读取它,必须将其分配给另一个流,然后将新的可读流分配给.Body,然后允许它继续到控制器,读取返回的流并将其复制回.Body。
示例中间件类。(致谢: jarz.net | 日志记录中间件)
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LoggingMiddleware> _logger;
public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
{
_logger = logger;
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
string responseBodyString = string.Empty;
try
{
// Swap the original Response.Body stream with one we can read / seek
Stream originalResponseBody = context.Response.Body;
using MemoryStream replacementResponseBody = new …Run Code Online (Sandbox Code Playgroud) 我几乎尝试了一切。我的前端是用 vue js 开发的。后端在 Laravel 中。我们已经为另一个网站编写了 api,我们试图从该网站获取数据。如果直接访问该网站 Url,它会提供所有数据,但是当我尝试使用 axios 从我的网站访问它时,它会给出此错误。
Access to XMLHttpRequest at 'https://example.com/api/tickets/fetch_tickets?page=undefined' from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)
我试图获取数据的网站表单也在 Laravel 中构建。我创建了中间件并将其应用到 api 路由上。我添加了 chrome 扩展Allow Cors,它可以正常工作,但我们不能要求每个客户都使用该扩展。
我们从其他可以很好地访问数据的网站访问该网址。只有 vue js 应用程序会产生这些问题。
Vue代码
getTickets() {
axios.get( 'example.com/api/tickets/fetch_tickets?page=' + this.pagination.current, {
}).then((response) => {
// console.log(res.data.data)
// this.desserts = res.data.data;
// this.loadingprop = false;
this.desserts = response.data.data;
this.pagination.current = response.data.current_page;
this.pagination.total = response.data.last_page; …Run Code Online (Sandbox Code Playgroud) 通常,我可以像这样设置数据App并从中获取数据:web::Data
let pool = sqlx::MySqlPool::connect("mysql://xxx")
.await
.expect("Mysql Connect error!");
HttpServer::new(move || {
// set the data pool: Pool<MySQL>
App::new()
.data(pool.clone())
.service(web::resource("/home").route(web::get().to(get_xxx)))
})
.bind("0.0.0.0:8000")?
.run()
.await;
Run Code Online (Sandbox Code Playgroud)
// get the data: pool: Pool<MySQL> from argument.
pub async fn get_xxx(
pool: web::Data<Pool<MySql>>,
path: web::Path<String>,
) -> Result<HttpResponse, Error> {
let mut pool = pool.clone();
todo!()
}
Run Code Online (Sandbox Code Playgroud)
如何获取pool: Pool<MySQL>中间件?
这是中间件的示例:
use std::task::{Context, Poll};
use actix_service::{Service, Transform};
use actix_web::dev::{ServiceRequest, ServiceResponse};
use actix_web::{Error, HttpResponse};
use futures::future::{ok, Either, Ready};
pub struct CheckLogin; …Run Code Online (Sandbox Code Playgroud) 在 aspnetcore 3.1 中制作 UI 中间件的推荐方法是什么?
我正在尝试重现诸如squashbuckle之类的中间件的功能,消费者可以导入NuGet包,然后将其注册为:
app.UseMyCustomMiddleUI(c =>
{
c.RoutePrefix = "custom/ui";
});
Run Code Online (Sandbox Code Playgroud)
然后导航到http://localhost:5000/custom/ui将提供捆绑在我的 NuGet 包中的资源。
具体来说,如何打包 css、js 甚至 razor 页面等资源,以便在注册中间件时将它们暴露在某个路径上?
建议使用中间件的人static files。在 NuGet 包的上下文中,它是如何工作的,在该包中,我不提供来自文件系统的文件,而是提供嵌入在程序集中的文件(我猜测)
通过express,我们可以使用不同的中间件来处理get和post请求,例如。
// GET method route
app.get('/users', function (req, res) {
// handle get request
})
// POST method route
app.post('/users', auth, function (req, res) {
// handle post request
})
Run Code Online (Sandbox Code Playgroud)
我如何在下一个js中做同样的事情?
我对 next js 完全陌生。我可能只是错过了一些东西。
我已按照指南将中间件插入我的页面之一。
在我在其中创建的子目录 /appstore 中,_middleware.js我试图获取一些内容来控制台日志,以便我知道该文件正在工作。
最终结果是我想检测它们是 android 还是 iOS 并将它们重定向到正确的商店。
import { NextFetchEvent, NextRequest } from 'next/server'
export function middleware() {
console.log('Hello, world!')
}
Run Code Online (Sandbox Code Playgroud)
但是,当我访问该页面时,我得到了 console.log = NULL ,所以显然有些事情不太正确?
我将 signalR hub 与 Websockets 结合使用,我需要创建一个中间件,该中间件将在 hub 上的每个方法上调用。我曾经使用上下文访问器,但它只有 http 请求,该请求具有连接到集线器的第一个请求,而不是在集线器上调用的实际方法。
//这行不通
rules.filter(rule => rule.type === 'redirect' && new RegExp(rule.rule).exec(pathname.slice(1)))
.map(rule => {
console.log('match');
const url = req.nextUrl.clone()
url.pathname = rule.destination
return NextResponse.redirect(url)
})
Run Code Online (Sandbox Code Playgroud)
//这确实有效
for (let rule of rules) {
const regex: RegExp = new RegExp(rule.rule)
if(regex.exec(pathname.slice(1)) && rule.type === 'redirect') {
console.log('match');
const url = req.nextUrl.clone()
url.pathname = rule.destination
return NextResponse.redirect(url)
}
}
Run Code Online (Sandbox Code Playgroud)
中间件已经通过 de for 循环运行良好
我尝试访问Next.js 中间件request.headers中的,但数据未显示。
如果我访问其他内容,数据就会出现。如果我显示标题,则会出现错误:
Server Error
TypeError: Cannot delete property 'Symbol(set-cookie)' of #<HeadersList2>
Run Code Online (Sandbox Code Playgroud)
Server Error
TypeError: Cannot delete property 'Symbol(set-cookie)' of #<HeadersList2>
Run Code Online (Sandbox Code Playgroud)
在请求变量中填写数据:
当我显示时出错request.headers:
middleware ×10
next.js ×4
asp.net-core ×3
api ×2
c# ×2
.net-core ×1
actix-web ×1
cors ×1
http-headers ×1
http-method ×1
httpclient ×1
javascript ×1
laravel ×1
nodes ×1
refit ×1
rust ×1
signalr-hub ×1
vue.js ×1