我想在我的ASP.NET应用程序中运行"后台作业"(定期,作为单独的线程).我需要主机名(DNS名称或IP)来完成我的任务.问题是HttpContext.Current这里可能没有(它的NULL).
有没有办法让主机名不使用HttpContext.Current.Request.Url.Host.
我们有一个依赖于的类HttpContext.我们已经实现了这样:
public SiteVariation() : this(new HttpContextWrapper(HttpContext.Current))
{
}
public SiteVariation(HttpContextBase context)
{}
Run Code Online (Sandbox Code Playgroud)
现在我想要做的是实例化SiteVariation类Unity,所以我们可以创建一个构造函数.但我不知道如何HttpContextWrapper(HttpContext.Current))在配置方式中在Unity中配置这个新功能.
ps这是我们使用的配置方式
<type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" />
Run Code Online (Sandbox Code Playgroud) 我目前正在研究ac #web API.对于特定的调用,我需要使用对API的ajax调用发送2个图像,以便API可以将它们保存为数据库中的varbinary(max).
Image或byte[]从HttpContent对象中提取?-
var authToken = $("#AuthToken").val();
var formData = new FormData($('form')[0]);
debugger;
$.ajax({
url: "/api/obj/Create/",
headers: { "Authorization-Token": authToken },
type: 'POST',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
Run Code Online (Sandbox Code Playgroud)
-
public async Task<int> Create(HttpContent content)
{
if (!content.IsMimeMultipartContent())
{
throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");
}
return 3;
}
Run Code Online (Sandbox Code Playgroud) 我一直在使用Hanselman博客上发现的MvcMockHelpers类来传递一个模拟的 HttpContext.我们对它进行了一些扩展,以添加我们需要的一些身份验证数据,而且大多数情况下这都很棒.
我们遇到的问题是我们给控制器的上下文在HttpContext.Response.Output中有一个空值,这会导致抛出一些异常.我不确定要添加什么才能使其正常工作.
这是现有的FakeHttpConext()方法:
public static HttpContextBase FakeHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
// Our identity additions ...
var user = new Mock<IPrincipal>();
OurIdentity identity = (OurIdentity)Thread.CurrentPrincipal.Identity;
context.Expect(ctx => ctx.Request).Returns(request.Object);
context.Expect(ctx => ctx.Response).Returns(response.Object);
context.Expect(ctx => ctx.Session).Returns(session.Object);
context.Expect(ctx => ctx.Server).Returns(server.Object);
context.Expect(ctx => ctx.User).Returns(user.Object);
context.Expect(ctx => ctx.User.Identity).Returns(identity);
return context.Object;
}
Run Code Online (Sandbox Code Playgroud)
这是爆炸方法(它是MVC Contrib项目的XmlResult的一部分):
public override void ExecuteResult(ControllerContext context)
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个包装类来处理HttpContext的内容.我正在创建一个cookie但无法添加到HttpContext.Request或Response cookies集合.
我正在使用Moq.我也使用以下链接中的MvcMockHelp:http: //www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
当我尝试在以下代码中添加到Cookies集合时:
HttpContextBase c1 = MvcMockHelpers.FakeHttpContext();
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "Tom";
c1.Request.Cookies.Add(aCookie); <------ Error here
Run Code Online (Sandbox Code Playgroud)
我在第4行代码c1.Request.Cookies.Add(aCookie)上得到以下错误;
Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
我也试过如下实例化上下文对象,但仍然没有运气
HttpContextBase c = MvcMockHelpers.FakeHttpContext
("~/script/directory/NAMES.ASP?city=irvine&state=ca&country=usa");
Run Code Online (Sandbox Code Playgroud)
我看到Request中的Cookies集合是NULL.我如何实例化它?
我也试过以下但没有运气.
c1.Request.Cookies["userName"].Value = "Tom";
Run Code Online (Sandbox Code Playgroud)
请让我知道我做错了什么.
我正在开发一个ASP.NET Web Api项目,并使其接受url中的版本信息.
例如:
- API/V1/myController的
- API/V2/myController的
现在我想在自定义LayoutRenderer中获取请求版本v1,v2Nlog.通常我会像下面的例子那样做.
[LayoutRenderer("Version")]
public class VersionLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, NLog.LogEventInfo logEvent)
{
var version = HttpContext.Current.Request.RequestContext.RouteData.Values["Version"];
builder.Append(version);
}
}
Run Code Online (Sandbox Code Playgroud)
问题: HttpContext.Current是NULL
我相信这是因为我使用异步包装为NLog与记录仪前几个电话也是Async.
在Ninject.Extensions.WebApi.UsageLogger中将记录器称为Async的示例.此时,HttpRequestMessage我们需要获取版本所需的所有信息.
/// <summary>
/// Initializes a new instance of the <see cref="UsageHandler" /> class.
/// </summary>
public UsageHandler()
{
var kernel = new StandardKernel();
var logfactory = kernel.Get<ILoggerFactory>();
this.Log = logfactory.GetCurrentClassLogger();
}
protected override async Task<HttpResponseMessage> …Run Code Online (Sandbox Code Playgroud) 我的一个服务使用IIS通过此类代码提供的服务器变量
var value = System.Web.HttpContext.Current.Request.ServerVariables["MY_CUSTOM_VAR"];
Run Code Online (Sandbox Code Playgroud)
我试过的是模拟那些对象并插入我自己的变量/集合并检查几个案例(例如变量丢失,值为null ...)我能够创建HttpContext,HttpRequest,HttpResponse的实例并分配它们但是它们中的每一个都只是一个没有接口或虚拟属性的普通类,并且ServerVariables的初始化发生在某个地方.
HttpContext嘲笑:
var httpRequest = new HttpRequest("", "http://excaple.com/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContextMock = new HttpContext(httpRequest, httpResponse);
HttpContext.Current = httpContextMock;
Run Code Online (Sandbox Code Playgroud)
尝试#1通过反射调用私有方法
var serverVariables = HttpContext.Current.Request.ServerVariables;
var serverVariablesType = serverVariables.GetType();
MethodInfo addStaticMethod = serverVariablesType.GetMethod("AddStatic", BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic);
addStaticMethod.Invoke(serverVariables, new object[] {"MY_CUSTOM_VAR", "value"});
Run Code Online (Sandbox Code Playgroud)
失败,错误表明集合是只读的.
尝试#2用我自己的实例替换ServerVariables
var request = HttpContext.Current.Request;
var requestType = request.GetType();
var variables = requestType.GetField("_serverVariables", BindingFlags.Instance | BindingFlags.NonPublic);
variables.SetValue(request, new NameValueCollection
{ …Run Code Online (Sandbox Code Playgroud) 我需要在我的基本实体上实现AddedBy/ChangedBy类型字段,所有其他实体都继承自(Fluent Nhibernate).
HttpContext.User.Identity从我的存储库/数据层访问可能不是一个好主意......或者是它?获取用户(当前身份)信息以记录添加或更改记录的人的最佳方法是什么?重新分解整个应用程序以在存储库调用中包含用户信息将是愚蠢的.我确信有更好,更通用的方式.
在 Node.js 和 Express 框架中,当它适用于 GET 时,我无法从 HTTP 上下文中检索 POST 和 PUT 请求的值。我正在使用 httpContext 设置唯一的 requestId 标识符,以便在记录跟踪 API 请求时可以使用它。
我发现 HttpContext 可以被中间件中的其他一些包重置,是否有更好的方法来存储可以在所有模块中访问的请求范围的数据。
app.js 文件
const app = express();
app.use(httpContext.middleware);
//Assign unique identifier to each req
app.use(function (req, res, next) {
let test = uuidv1();
httpContext.set("reqId", test);
next();
});
const PORT = process.env.PORT || 3001;
Connection.setupPool();
app.use(express.json());
app.use(helmet());
if (app.get("env") === "development") {
app.use(morgan("tiny"));
}
//use to access a resource in the root through url
app.use(express.static("resource"));
app.use("/users", userRouter);
//Code For Instagram …Run Code Online (Sandbox Code Playgroud) 我无法访问控制器外部的会话变量,他们建议您添加超过 200 个示例;
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)
并使用
public class DummyReference
{
private IHttpContextAccessor _httpContextAccessor;
public DummyReference(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void DoSomething()
{
// access _httpcontextaccessor to reach sessions variables
}
}
Run Code Online (Sandbox Code Playgroud)
但是,没有人提到如何从我的控制器调用此类。我怎样才能到达那个班级?
如果将其更改为静态,那么我需要绕过构造。如果我创建它,我需要 httpcontextaccessor 来构造。
对于想要了解更多为什么我这样做的人,我想编写包含加密、解密数据库表 RowID 之类的方法的类,以便使用 value+sessionvariable 在 VIEW 中进行屏蔽,以确保其不被修改。
另外,我希望 DummyReference 是静态的,这样我可以轻松访问 DummyReference.EncryptValue 或 DecryptValue。
httpcontext ×10
c# ×7
asp.net ×3
asp.net-mvc ×3
moq ×2
.net-core ×1
bytearray ×1
express ×1
hostname ×1
httprequest ×1
mocking ×1
ninject ×1
node.js ×1
reflection ×1
session ×1
stream ×1
tdd ×1
unit-testing ×1