小编Lar*_*ard的帖子

在ASP.NET Core应用程序中将HTTPS站点重定向到非www

我正在建立我的第一个ASP.NET核心应用程序.此应用程序在HTTPS上运行.目前,我有两个响应的域:domain.dkwww.domain.dk,我想301重定向wwwnon www.

我google了很多,最后添加了以下类:

public class NonWwwRule : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        var req = context.HttpContext.Request;
        var currentHost = req.Host;
        if (currentHost.Host.StartsWith("www."))
        {
            var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
            var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            context.HttpContext.Response.Redirect(newUrl.ToString());
            context.Result = RuleResult.EndResponse;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将其添加到Configure我的方法中Startup.cs:

var options = new RewriteOptions();
options.Rules.Add(new NonWwwRule());
app.UseRewriter(options);
Run Code Online (Sandbox Code Playgroud)

但是,我的网站仍然没有回应这个,两者都www没有作品.

编辑:

我添加了日志记录 在我ApplyRule,我发送垃圾邮件:

    public void ApplyRule(RewriteContext context) …
Run Code Online (Sandbox Code Playgroud)

c# url-rewriting asp.net-core asp.net-core-2.0

7
推荐指数
1
解决办法
1156
查看次数

代表和调用列表

我正在ASP.NET中创建一个较小的RPG游戏.在这个游戏中,我有一个项目架构,每个项目都有一些方法.例如,所有项目应共享" 丢弃 "," 检查 "和" 使用 "等方法.有些项目必须使用" 操作 "," 计算 "等方法进行扩展.

到目前为止,我已经创建了以下对象GameActionList:

public delegate void MyDelegate();

public class GameActionList
{
    public List<MyDelegate> Items = new List<MyDelegate>();

    public void Add(MyDelegate del)
    {
        Items.Add(del);
    }

    public void CallDelegates()
    {
        foreach (MyDelegate myDelegate in Items)
        {
            myDelegate();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个BaseItem类,它有这个GameActionList.BaseItem类中的get属性是这样的:

    public GameActionList Actions 
    { 
        get
        {
            GameActionList actions = new GameActionList();
            actions.Add(this.Drop);
            actions.Add(this.Examine);
            return actions;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这很好,但是......我有一些问题!

我的问题

我需要一种更通用的GameActionList方式.我需要有一个列表,不仅有空洞,还有函数.另外,我需要两个带参数和无参数的方法.

例如:Drop方法需要一个Player对象,因此他可以删除该项.该检查方法需要返回一个字符串descriping的项目.

另外,我需要一些我在初始化GameActionList时不知道的数据:我在调用方法时首先知道这些数据...

所以我有两个问题:

  1. 你如何扩展GameActionList,所以它可以包含空洞和函数的列表,并且这些都可以有参数或者没有..(并且它甚至有感觉?)
  2. 如何在循环的后期向该方法提供一些数据,比如在调用时?

另外......这可能是一个非常愚蠢的方法,所以如果你有一些更优雅的解决方案..我已经准备好听了!

非常感谢...!拉尔斯

c# asp.net delegates invoke

6
推荐指数
1
解决办法
1万
查看次数

调用API:如何提供这些参数(键,随机数和签名)

我正在玩实现API.通常这很简单,但这个给我带来了麻烦.但是,我很确定问题是我,而不是API.

此特定API的网址:

https://www.bitstamp.net/api/

我想对"帐户余额"进行POST调用.目前我得到以下答案:

{"error": "Missing key, signature and nonce parameters"}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码执行此操作:

        var path = "https://www.bitstamp.net/api/user_transactions";
        var nonce = GetNonce();
        var signature = GetSignature(nonce);

        using (WebClient client = new WebClient())
        {

            byte[] response = client.UploadValues(path, new NameValueCollection()
           {
               { "key", Constants.ThirdParty.BitStamp.ApiKey },
               { "signature", signature },
               { "nonce", nonce},

           });
            var str = System.Text.Encoding.Default.GetString(response);
        }

        return 0.0m;
Run Code Online (Sandbox Code Playgroud)

这是我的两个辅助函数:

    private string GetSignature(int nonce)
    {
        string msg = string.Format("{0}{1}{2}", nonce,
            Constants.ThirdParty.BitStamp.ClientId,
            Constants.ThirdParty.BitStamp.ApiKey);

        return HelperFunctions.sign(Constants.ThirdParty.BitStamp.ApiSecret, msg);
    }

    public static int GetNonce() …
Run Code Online (Sandbox Code Playgroud)

c# api post c#-4.0

6
推荐指数
1
解决办法
4179
查看次数

发布ASP.NET核心应用程序:命令"npm install"退出,代码为9009

我有一个带有React前端的ASP.NET Core解决方案.我现在有一个问题,我无法使用Visual Studio中的正常发布窗口释放代码.我发布到Azure网络应用程序内的Web应用程序,它可以完美地用于我所有其他以相同方式构建的解决方案.

代码在本地完美运行,我可以在npm install本地运行而不会出现问题.

发布时,错误显然来自某些未找到的文件.在我的项目文件中,我一直在调试,发现这是一个挑战:

 <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec Command="npm install" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --env.prod" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="wwwroot\dist\**" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>
Run Code Online (Sandbox Code Playgroud)

Visual Studio中的错误:

Severity    Code    Description Project File    Line    Suppression State
Error       The command "npm …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-core-mvc npm-install asp.net-core asp.net-core-2.0

6
推荐指数
1
解决办法
8196
查看次数

C#:输入流不是有效的二进制格式

我在C#/ ASP.NET中反序列化有问题,它给出了确切的错误:

输入流不是有效的二进制格式.起始内容(以字节为单位)为:41-41-45-41-41-41-44-2F-2F-2F-2F-2F-41-51-41-41-41 ...

我想做什么

我有一个有3个班级的结构.我有一个类A,它是一个基类,然后是B和C,它们是从A派生的.

我试图在类型为VARCHAR(MAX)的列中使用LINQ to SQL在数据库中存储随机类型的B和C. 我不能使用BINARY,因为长度大约是15.000.

我的代码......

错误位于LAST代码块中

业务层中的C#代码 - 存储记录

    private void AddTraceToDatabase(FightTrace trace)
    {
        MemoryStream recieverStream = new MemoryStream();
        MemoryStream firedStream = new MemoryStream();
        MemoryStream moveStream = new MemoryStream();

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(recieverStream,trace.Reciever);
        binaryFormatter.Serialize(firedStream,trace.FiredBy);
        binaryFormatter.Serialize(moveStream,trace.Move);

        string reciever = Convert.ToBase64String(recieverStream.ToArray());
        string fired = Convert.ToBase64String(firedStream.ToArray());
        string move = Convert.ToBase64String(moveStream.ToArray());


        this.dataAccess.AddFightTrace(trace.TraceType.ToString(),reciever,move,fired,trace.DateTime,this.FightId);
    }
Run Code Online (Sandbox Code Playgroud)

数据访问层中的C#代码 - 存储记录

    public void AddFightTrace(string type, string reciever, string Move, string firedBy, DateTime firedAt, int fightid)
    {
        GameDataContext db = new GameDataContext(); …
Run Code Online (Sandbox Code Playgroud)

c# sql asp.net serialization linq-to-sql

5
推荐指数
1
解决办法
1万
查看次数

从连接节点列表中绘制图形

在一个系统中,我有一个节点列表,它们像普通图一样连接.我们知道整个系统及其所有连接,我们也有一个起点.我所有的边都有一个方向.

现在我想自动绘制所有这些节点和边.问题不是实际绘图,而是计算(x,y)坐标.所以基本上我想绘制整个图表,看起来不错.

我的数据结构类似于:

class node:
string text
List<edge> connections
Run Code Online (Sandbox Code Playgroud)

这个问题必定有一些众所周知的算法吗?我找不到任何,但我可能使用了错误的关键字.

我的想法:

一种方法是将我们的startnode定位在(0,0),然后得到一些常量,即"距离".然后,对于每个邻居,它将向y位置添加距离,并且对于作为邻居的每个节点,设置x =距离*n.

但这确实会带来很多问题 - 所以这肯定不是要走的路.

algorithm graph edges coordinates nodes

5
推荐指数
1
解决办法
2127
查看次数

HttpHandler生成的内容(axd文件 - 捆绑css/js)给出了404错误.使用Combres

我想捆绑和缩小我的JS/CSS文件.要做到这一点,我正在使用Combres.

我在我的本地环境中设置了Combres解决方案,它在那里工作.但是,当我将我的应用程序部署到IIS时,它不起作用.UM-HM.我尝试访问的网址是http://www.mysite.com/combres.axd/siteJs/-1639413070/.

我收到IIS 404错误:404 - 找不到文件或目录.

这是我的设置.

Web.config文件:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
    <section name="combres" type="Combres.ConfigSectionSetting, Combres, Version=2.2, Culture=neutral, PublicKeyToken=1ca6b37997dd7536" />
  </configSections>
  <appSettings>
    <add key="ChartImageHandler" value="storage=session;timeout=20;"/>
        <add key="CombresSectionName" value="combres" />
  </appSettings>

  <system.web>
    <httpModules>
      <add name="MinifyHtml" type="GKBusiness.HtmlMinifier.MinifyHtmlClass,GKBusiness"/>
    </httpModules>
    <globalization culture="da-DK" uiCulture="da-DK"/>
    <httpHandlers>
        <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
        <add …
Run Code Online (Sandbox Code Playgroud)

asp.net iis web-config httphandler combres

5
推荐指数
1
解决办法
1744
查看次数

如何对使用缓存的服务进行单元测试?

我有一个服务层,其中包含多种方法。这些方法已实现缓存,如下所示:

string key = "GetCategories";
if (CacheHandler.IsCachingEnabled() && !CacheHandler.ContainsKey(key))
{
    var categories = RequestHelper.MakeRequest("get_category_index")["categories"];
    var converted = categories.ToObject<List<Category>>();
    CacheHandler.InsertToCache(key,converted);
    return converted;
}
return CacheHandler.GetCache(key) as List<Category>;
Run Code Online (Sandbox Code Playgroud)

现在,问题是我也想进行单元测试,如下所示:

[TestMethod]
public void GetCategories()
{
    IContentService contentService = new ContentService();
    var resp = contentService.GetCategories();
    Assert.IsNotNull(resp,"Should not be null");
}
Run Code Online (Sandbox Code Playgroud)

问题是,在单元测试期间,HttpContext.Current内部my CacheHandler为空(显然)。

解决此问题的最简单方法是什么?

(请尽可能具体,因为我之前没有做过很多单元测试)

c# asp.net-mvc caching unit-testing

5
推荐指数
1
解决办法
7501
查看次数

使用字符串作为键迭代JavaScript对象

我正在构建一个JavaScript数组,它有字符串作为键.

数组应该在每个条目都有一个对象.我的对象看起来像这样(console.log我的变量之一rIds):

Firebug我变量的截图

现在,此对象的长度为0,这使得无法迭代它.

我想迭代每个键,所以我可以检索并访问我的id列表(rIds[key].productIds).

代码:

var rIds = [];
        var response = RR.data.JSON.placements;

        console.log(response);
        $(response).each(function (placementId) {
            var placement_name = this.placement_name;

            rIds[this.placement_name] = {
                productIds: []
            };

            $(this.recs).each(function (recIndex) {
                var pid = this.pid;
                pid = getRandomId(19341610, 19341746);
                rIds[placement_name].productIds[recIndex] = pid;
            });
        });

        var count = '<%=ViewBag.Get("RecommendationCount") %>';

        console.log(rIds);
        console.log(rIds.length);
        $.each(rIds, function (index, val) {
            console.log(val);  // This should work as expected.
        });
Run Code Online (Sandbox Code Playgroud)

我尝试了什么?

我找到了以下片段,它在IE8中不起作用.但是,即使Object.keys(rIds).length得到正确的长度,这也无济于事.

for (var index = 0; index …
Run Code Online (Sandbox Code Playgroud)

javascript jquery

5
推荐指数
1
解决办法
275
查看次数

ASP.NET Core 路由到其他方法而不是 HttpGet 路由中的我的名称

我的 ASP.NET 核心应用程序中有一个简单的控制器。想法是调用控制器CreditData,例如,我的端点可以是/api/creditdata/,然后它应该具有默认的预期 API 方法。

我有两种方法:

  • /api/creditdata 它应该有一个查询,例如 /api/creditdata?query=text1,text2
  • /api/creditdata/value像这样的查询/api/creditdata/text1应该在哪里工作

我尝试将其设置如下:

   [Route("api/[controller]")]
    public class CreditDataController : Controller
    {
        private CreditDataService _creditDataService;
        public CreditDataController()
        {
            _creditDataService = new CreditDataService();
        }

        // GET: api/CreditData?query=text1,text2
        [HttpGet("{query}", Name = "Get")]
        public List<CreditData> Get([FromQuery] string query)
        {
            // code
        }

        // GET: api/CreditData/GetByRegistration/33514322
        [HttpGet("{query}", Name= "GetByRegistration")]
        public CreditData GetByRegistration(string query)
        {
            // code
        }


    }
Run Code Online (Sandbox Code Playgroud)

我有一个非常标准的Startup.cs文件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            { …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-core-mvc asp.net-core asp.net-core-2.0

5
推荐指数
1
解决办法
4192
查看次数